package com.rainng.coursesystem.service.teacher;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rainng.coursesystem.dao.mapper.CourseMapper;
import com.rainng.coursesystem.dao.mapper.ExamMapper;
import com.rainng.coursesystem.model.bo.ExamDTO;
import com.rainng.coursesystem.model.entity.CourseEntity;
import com.rainng.coursesystem.model.entity.ExamEntity;
import com.rainng.coursesystem.model.vo.response.ResultVO;
import com.rainng.coursesystem.model.vo.response.table.ExamVO;
import com.rainng.coursesystem.service.BaseService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service("teacher_service")
public class ExamService extends BaseService {

    @Autowired
    private CourseMapper courseMapper;

    @Autowired
    private ExamMapper examMapper;

    public ResultVO listExam() {

        Integer teacherId = getUserId();
        List<CourseEntity> courseList = courseMapper.selectList(new QueryWrapper<CourseEntity>().eq("course_teacher_id", teacherId));
        List<Integer> courseIds = courseList.stream().map(c -> c.getId()).collect(Collectors.toList());

        List<ExamEntity> examList = examMapper.selectList(new QueryWrapper<ExamEntity>().in("course_id", courseIds));
        Map<Integer, CourseEntity> courseMap = courseList.stream().collect(Collectors.toMap(CourseEntity::getId, c -> c));

        List<ExamVO> voList = new ArrayList<>();
        for (ExamEntity examEntity : examList) {
            ExamVO vo = new ExamVO();
            BeanUtils.copyProperties(examEntity,vo);
            String courseName = courseMap.get(vo.getCourseId()).getName();
            vo.setCourseName(courseName);

            voList.add(vo);
        }

        return result(voList);

    }

    public ResultVO addExam(ExamDTO dto) {

        ExamEntity examEntity = new ExamEntity();
        BeanUtils.copyProperties(dto,examEntity);
        LocalDateTime endTime = dto.getBeginTime().plusMinutes(dto.getDuration());
        examEntity.setEndTime(endTime);
        examEntity.setStatus(0);
        examMapper.insert(examEntity);

        return result("success");

    }

    public ResultVO updateExam(Integer id, ExamDTO dto) {

        ExamEntity examEntity = new ExamEntity();
        BeanUtils.copyProperties(dto,examEntity);
        examEntity.setId(id);
        examMapper.updateById(examEntity);
        return result("success");
    }

    public ResultVO deleteExam(Integer id) {
        examMapper.deleteById(id);
        return result("success");
    }
}
